<template>
	<view class="page-cont">
		<navbar title="能耗查看"></navbar>
		<view class="main-cont" :style="{height: pageHeight}">
			<!-- 项目切换 -->
			<view class="device-select" @click="handleOpen">
				<view class="device-name">{{deviceName}}</view>
				<image class="device-arrow" :src="isOpen ? '/static/up_black.png' : '/static/down_black.png'"></image>
			</view>
			<!-- tab栏 -->
			<tab :tabActive="tabActive" :tabs="tabs" @tabChange="handleTabChange"></tab>
			<view class="box-cont">
				<!-- 统计数据 -->
				<view class="stat-cont">
					<view class="stat-item">
						<view class="stat-item-name">{{titleName}}</view>
						<view class="stat-item-value">{{formatDecimal(statData.num1)}}<text
								class="stat-item-unit">{{unit}}</text>
						</view>
					</view>
					<view class="stat-item">
						<view class="stat-item-name">日均值</view>
						<view class="stat-item-value">{{formatDecimal(statData.num2)}}<text
								class="stat-item-unit">{{unit}}</text>
						</view>
					</view>
				</view>
				<!-- 用电明细 -->
				<view class="ledger-cont">
					<view class="section">
						<view class="section-title">用电明细</view>
						<image class="section-arrow" src="/static/fullscreen.png" @click="handleFullScreen(0)"></image>
					</view>
					<view class="ledger-cont-calendar">
						<CheckCalendar ref="calendar"></CheckCalendar>
					</view>
				</view>
				<!-- 用电对比 -->
				<view class="compare-cont">
					<view class="section">
						<view class="section-title">用电对比</view>
						<image class="section-arrow" src="/static/fullscreen.png" @click="handleFullScreen(1)"></image>
					</view>
					<CheckCompareBar class="compare-cont-bar" ref="compareBar"></CheckCompareBar>
				</view>
				<!-- 用电组成 -->
				<view class="element-cont">
					<view class="section">
						<view class="section-title">用电组成</view>
						<image class="section-arrow" src="/static/fullscreen.png" @click="handleFullScreen(2)"></image>
					</view>
					<CheckElementBar class="element-cont-bar" ref="elementBar"></CheckElementBar>
				</view>
			</view>
		</view>
		<!-- 弹框选择设备 -->
		<uni-popup ref="popup" type="bottom" background-color="#fff" @maskClick="isOpen = false">
			<scroll-view class="popup-cont" scroll-y>
				<view class="popup-header">请选择</view>
				<view class="popup-title" v-for="(item, index) in deviceList" :key="index"
					@click="handleDeviceChange(item)">{{item.name}}</view>
			</scroll-view>
		</uni-popup>
	</view>
</template>
<script setup lang="ts">
	import { reactive, ref, getCurrentInstance, watch } from 'vue';
	import { onShow, onLoad, onUnload } from "@dcloudio/uni-app";
	import { useNavbar } from "@/utils/hooks.js";
	import CheckCompareBar from './components/check-compare-bar.vue';
	import CheckElementBar from './components/check-element-bar.vue';
	import CheckCalendar from './components/check-calendar.vue';
	import { useEnergyCheck } from '@/store/energy-check'
	import * as energy from "@/api/energy.ts";

	const energyCheck = useEnergyCheck()

	const { proxy } = getCurrentInstance();
	const { pageHeight } = useNavbar();
	const tabs = ref(["电费", "耗能"]);
	const tabActive = ref(0)
	const radioActive = ref(1)
	const calendarActive = ref(0)

	const titleName = ref("本月电费")
	const unit = ref("元")
	//当前电表名称
	const deviceName = ref()
	//当前电表ID
	const deviceId = ref()
	//
	const isOpen = ref(false)
	const popup = ref()
	const deviceList = ref([])
	const calendarList = ref([])
	const statData = reactive({
		num1: 0,
		num2: 0
	})

	//用电明细
	const calendar = ref();
	//用电对比
	const compareBar = ref();
	//用电组成
	const elementBar = ref();

	const projectId = ref<number>()

	// 监听用电明细：维度筛选
	watch(() => radioActive.value, (val) => {

	});
	// 监听用电明细：日历点击
	watch(() => calendarActive.value, (val) => {
		// console.log(calendarList.value[val].time);
	});

	onLoad((query ?: AnyObject | undefined) => {
		projectId.value = Number(query?.projectId);
		if (query?.oid != undefined) {
			deviceId.value = Number(query?.oid);
			console.log("deviceId.value = ", deviceId.value)
		}
		initProject();
	});

	onUnload(() => {
		energyCheck.clearData;
	})

	const initProject = async () => {
		const pobjResult = await energy.getProjectObjects({ "pmid": projectId.value })
		//50电表
		deviceList.value = [];
		deviceList.value.push(...pobjResult.modus["50"]);
		if (deviceId.value != undefined && deviceName.value == undefined) {
			for (var i = 0; i < deviceList.value.length; i++) {
				console.log(deviceList.value[i])
				if (deviceId.value == deviceList.value[i].id) {
					deviceName.value = deviceList.value[i].name;
					break;
				}
			}
		} else {
			deviceName.value = deviceList.value[0].name;
			deviceId.value = deviceList.value[0].id;
		}

		initData();

		initElement();
	}

	const initData = async () => {

		const startMonth = proxy.dayjs().startOf('month').format("YYYY-MM-DD");//当月的第一天
		const endMonth = proxy.dayjs().endOf('month').format("YYYY-MM-DD");//当月的最后一天
		const startTime = proxy.dayjs(startMonth).startOf('week').add(1, 'day').format("YYYY-MM-DD");//当月第一天所在周的周一
		const endTime = proxy.dayjs(endMonth).endOf('week').add(1, 'day').format("YYYY-MM-DD");//当月最后一天所在周的周日

		const key = tabActive.value == 0 ? energy.GartherType.dwpfmdf : energy.GartherType.xmznh;

		//本月电量
		const sumResult = await energy.getDataByTUOKs({
			"startTime": proxy.dayjs().format("YYYY-MM"), "endTime": proxy.dayjs().format("YYYY-MM"),
			"format": energy.FormatType.month, "oper": energy.OperType.sum, "keys": `50_0_${deviceId.value}_${key}`
		});
		statData.num1 = 0;
		if (sumResult[`50_0_${deviceId.value}_${key}`].length > 0) {
			statData.num1 = sumResult[`50_0_${deviceId.value}_${key}`][0].value;
		}

		//日均值
		const avgResult = await energy.getDataByTUOKs({
			"startTime": proxy.dayjs().format("YYYY-MM"), "endTime": proxy.dayjs().format("YYYY-MM"),
			"format": energy.FormatType.month, "oper": energy.OperType.avg, "keys": `50_0_${deviceId.value}_${key}`
		});
		statData.num2 = 0;
		if (avgResult[`50_0_${deviceId.value}_${key}`].length > 0) {
			statData.num2 = avgResult[`50_0_${deviceId.value}_${key}`][0].value;
		}

		//每日数据
		const dataResult = await energy.getDataByTUOKs({
			"startTime": startTime, "endTime": endTime,
			"format": energy.FormatType.day, "oper": energy.OperType.coun, "keys": `50_0_${deviceId.value}_${key}`
		});

		console.log("当前 ", startTime, endTime)
		console.log("去年 ", proxy.dayjs(startTime).subtract(1, 'year').format("YYYY-MM-DD"),
			proxy.dayjs(endTime).subtract(1, 'year').format("YYYY-MM-DD"))
		//去年数据 - 计算同比
		const lastYearResult = await energy.getDataByTUOKs({
			"startTime": proxy.dayjs(startTime).subtract(1, 'year').format("YYYY-MM-DD"),
			"endTime": proxy.dayjs(endTime).subtract(1, 'year').format("YYYY-MM-DD"),
			"format": energy.FormatType.day, "oper": energy.OperType.coun, "keys": `50_0_${deviceId.value}_${key}`
		});

		if (lastYearResult[`50_0_${deviceId.value}_${key}`].length > 0 && dataResult[`50_0_${deviceId.value}_${key}`].length > 0) {
			lastYearResult[`50_0_${deviceId.value}_${key}`].forEach(lastItem => {
				dataResult[`50_0_${deviceId.value}_${key}`].some(item => {
					// if (proxy.dayjs(lastItem.time).format("MM-DD") == proxy.dayjs(item.time).format("MM-DD")) {
					if (proxy.dayjs(item.time).diff(lastItem.time, 'year') == 1) {
						item.tongbi = `${formatDecimal((item.value - lastItem.value) / lastItem.value * 100)}%`
						return false;
					} else {
						return true;
					}
				})
			})
		}

		console.log("上月", proxy.dayjs(startTime).subtract(1, 'month').format("YYYY-MM-DD"),
			proxy.dayjs(endTime).subtract(1, 'month').format("YYYY-MM-DD"))
		//上月数据 - 计算环比
		const lastMonthResult = await energy.getDataByTUOKs({
			"startTime": proxy.dayjs(startTime).subtract(1, 'month').format("YYYY-MM-DD"),
			"endTime": proxy.dayjs(endTime).subtract(1, 'month').format("YYYY-MM-DD"),
			"format": energy.FormatType.day, "oper": energy.OperType.coun, "keys": `50_0_${deviceId.value}_${key}`
		});

		if (lastMonthResult[`50_0_${deviceId.value}_${key}`].length > 0 && dataResult[`50_0_${deviceId.value}_${key}`].length > 0) {
			lastMonthResult[`50_0_${deviceId.value}_${key}`].forEach(lastItem => {
				dataResult[`50_0_${deviceId.value}_${key}`].some(item => {
					//todo 比较日
					// if (proxy.dayjs(lastItem.time).format("YYYY-DD") == proxy.dayjs(item.time).format("YYYY-DD")) {
					if (proxy.dayjs(item.time).diff(lastItem.time, 'month') == 1) {
						item.huanbi = `${formatDecimal((item.value - lastItem.value) / lastItem.value * 100)}%`
						return false;
					} else {
						return true;
					}
				})
			})
		}


		calendar.value.initCalendar(dataResult[`50_0_${deviceId.value}_${key}`]);

		compareBar.value.initData(`50_0_${deviceId.value}_${key}`, dataResult, lastMonthResult);

		energyCheck.setKey(`50_0_${deviceId.value}_${key}`);
		energyCheck.setData(dataResult);
		energyCheck.setLastData(lastMonthResult);
	}


	const initElement = async () => {
		const key = tabActive.value == 0 ? energy.GartherType.dwpfmdf : energy.GartherType.xmznh;
		let keys = []
		deviceList.value.forEach(item => {
			keys.push(`50_0_${item.id}_${key}`)
		})
		//所有电表
		const sumResult = await energy.getDataByTUOKs({
			"startTime": proxy.dayjs().format("YYYY-MM"), "endTime": proxy.dayjs().format("YYYY-MM"),
			"format": energy.FormatType.month, "oper": energy.OperType.sum, "keys": keys
		});

		energyCheck.setType(key);
		energyCheck.setPobj(deviceList.value);
		energyCheck.setPobjData(sumResult);

		elementBar.value.initData(key, deviceList.value, sumResult);
	}

	function handleOpen() {
		isOpen.value = true;
		popup.value.open();
	}

	// 菜单切换
	function handleTabChange(e) {
		tabActive.value = e;
		switch (tabActive.value) {
			case 0:
				titleName.value = "本月电费";
				unit.value = "元";
				break;
			case 1:
				titleName.value = "本月耗能"
				unit.value = "kw.h";
				break
		}
		initData();
		initElement();
	}

	// 设备切换
	function handleDeviceChange(e) {
		isOpen.value = false;
		popup.value.close();
		deviceName.value = e.name;
		deviceId.value = e.id;
		initData();
	}

	// 全屏
	function handleFullScreen(e) {
		if (e == 0) {
			// 用电明细
			uni.navigateTo({
				url: `/pages/energy/check-calendar`,
			});
		} else if (e == 1) {
			// 用电对比
			uni.navigateTo({
				url: `/pages/energy/check-compare`,
			});
		} else if (e == 2) {
			// 用电组成
			uni.navigateTo({
				url: `/pages/energy/check-element`,
			});
		}
	}

	function formatDecimal(num) {
		return num ? parseFloat(num.toFixed(2)).toString() : "-";
	}
</script>
<style lang="scss" scoped>
	.page-cont {
		.main-cont {}

		.device-select {
			height: 80rpx;
			line-height: 80rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			background-color: transparent;
			border-bottom: 1px solid #ccc;

			.device-name {
				color: #666;
				font-size: 28rpx;
			}

			.device-arrow {
				padding-left: 20rpx;
				width: 32rpx;
				height: 32rpx;
			}
		}

		.box-cont {
			padding: 20rpx;
		}

		.stat-cont {
			padding: 20rpx 30rpx;
			display: flex;
			border-radius: 10rpx;
			background: linear-gradient(90deg, #7E9CFF, #1D4ADA);
			box-sizing: border-box;

			.stat-item {
				width: 50%;
			}

			.stat-item-name,
			.stat-item-value,
			.stat-item-unit {
				color: #fff;
				font-size: 25rpx;
			}

			.stat-item-value {
				padding-top: 24rpx;
				font-size: 51rpx;
				font-weight: 600;
			}

			.stat-item-unit {
				padding-left: 10rpx;
				font-size: 26rpx;
				font-weight: 400;
			}
		}

		.ledger-cont,
		.compare-cont,
		.element-cont {
			margin-top: 20rpx;
			padding: 20rpx;
			border-radius: 10rpx;
			background-color: #fff;
		}

		.section {
			display: flex;
			justify-content: space-between;
			align-items: center;

			.section-title {
				color: #333;
				font-size: 28rpx;
				font-weight: 600;
			}

			.section-arrow {
				padding: 0 20rpx;
				width: 80rpx;
				height: 40rpx;
				box-sizing: border-box;
			}
		}

		.ledger-cont-calendar {
			margin-top: 30rpx;
		}

		.compare-cont-bar,
		.element-cont-bar {
			width: 100%;
			height: 400rpx;
		}
	}

	.popup-cont {
		background: #fff;
		max-height: 80vh;

		.popup-title,
		.popup-header {
			height: 100rpx;
			line-height: 100rpx;
			color: #333;
			font-size: 28rpx;
			text-align: center;
			border-top: 2rpx solid #eee;
		}

		.popup-header {
			font-size: 32rpx;
			font-weight: 600;
		}
	}
</style>